package com.xianxing.wxPay.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.xianxing.wxPay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private WXPay wxPay;
    @Override
    public Map nativePay(String orderId, Integer money) {

        if(!StringUtils.isEmpty(orderId)&&money>0){
            //封装数据
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("body", "先行");//商品描述
                map.put("out_trade_no", orderId);//订单号
                map.put("spbill_create_ip", "127.0.0.1");//终端ip
                BigDecimal fen = getMoneyToFen(money);
                map.put("total_fee", String.valueOf(fen));//支付金额 已分为单位
                map.put("notify_url", "http://www.baidu.com");//回调地址
                map.put("trade_type", "NATIVE");//交易类型
                //执行请求
                return wxPay.unifiedOrder(map);
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 对金额进行精确计算
     * @param money
     * @return 返回金额 单位为分
     */
    private BigDecimal getMoneyToFen(Integer money) {
        BigDecimal payMoney = new BigDecimal(money);
        BigDecimal fen = payMoney.multiply(new BigDecimal("100")); //1.00
        fen = fen.setScale(0, BigDecimal.ROUND_UP);//保留0为小数 向上取整
        return fen;
    }
}
